package com.example.demo.poc.example;

import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

import java.math.BigDecimal;
import java.util.Map;

public class AviatorMaxFunction extends AbstractVariadicFunction {

    private static final long serialVersionUID = 290911582762992375L;
    public static final String NAME ="max";
    @Override
    public AviatorObject variadicCall(Map<String, Object> map, AviatorObject... aviatorObjects) {

        BigDecimal val = getValue(aviatorObjects[0].getValue(map));
        int max = 0;
        for (int i = 1; i < aviatorObjects.length-1; i++) {
            BigDecimal tval = getValue(aviatorObjects[i].getValue(map));
            if(val.compareTo(tval) == -1){
                max = i;
            }
        }
        Object o = aviatorObjects[max].getValue(map);
        if(o instanceof Double){
            return AviatorRuntimeJavaType.valueOf((double)o);
        }else{
            return AviatorRuntimeJavaType.valueOf((long)o);
        }



    }

    private BigDecimal getValue(Object o){
        BigDecimal val = null;
        if(o instanceof Long){
            val= BigDecimal.valueOf((Long)o);
        }else if(o instanceof Double) {
            val= BigDecimal.valueOf((Double)o);
        }
        return val;
    }

    @Override
    public String getName() {
        return NAME;
    }
}
